import React from 'react';
import { Form, Modal, Select, message, Spin, Input } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getJobList } from '@/services/organization';
import { addFieldSet, getCategoryTree, getPositionKeywords } from '../../service';
import { queryChannelDicts } from '../../../service';
import DropDownCascader from '../DropDownCascader';

const { Option } = Select;

const MAX_COUNT = {
    bosszp: 1,
    lagou: 1,
    xmrc: 3,
    liepin: 3,
    mmzp: 1,
    linkedin: 3
};

const LAST_LEVEL = {
    bosszp: true,
    lagou: true,
    xmrc: false,
    liepin: true,
    mmzp: false,
    linkedin: false
};

const SKILL_MAX = {
    bosszp: 8,
    lagou: 4,
    mmzp: 1,
    linkedin: 10
};

const FORM_TITLE = {
    linkedin: {
        select: 'Select ',
        selectInput: 'Select or enter ',
        notNull: ' cannot be empty',
        title: 'Job title',
        category: 'Job function',
        skill: 'Target your job post',
        project: 'Add to a project'
    },
    mmzp: {
        category: '行业'
    }
};

const filterTree = tree =>
    tree.map(({ children, positionCategoryCode, positionCategoryName, ...props }) => ({
        children: children && children.length > 0 ? filterTree(children) : '',
        label: positionCategoryName,
        value: positionCategoryCode,
        ...props
    }));

const FieldModal = React.forwardRef(({ form, type, disabledPositionList = [], onRefresh }, ref) => {
    const { getFieldDecorator } = form;
    const [visible, setVisible] = React.useState(false);
    const [data, setData] = React.useState('');

    // 职位列表
    const { data: dutyList, loading: dutyLoading, run: fetchDutyList } = useRequest(getJobList, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return resData?.rows || [];
                }
                message.error(msg);
            }
            return [];
        }
    });

    // 职位类别树
    const { data: categoryTree, loading: categoryLoading, run: fetchCategoryTree } = useRequest(getCategoryTree, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return filterTree(resData || []);
                }
                message.error(msg);
            }
            return [];
        }
    });

    // 领英关键词
    const { data: linkedInKeywords, loading: linkedInKeywordsLoading, run: fetchLinkedInKeywords } = useRequest(
        () =>
            queryChannelDicts([
                {
                    categoryCode: 'positionKeyword',
                    channelCode: 'linkedin'
                },
                {
                    categoryCode: 'projectInfo',
                    channelCode: 'linkedin'
                }
            ]),
        {
            manual: true,
            formatResult: res => {
                if (res) {
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        const obj = {};
                        resData.forEach(item => {
                            obj[item.categoryCode] = item.channelSelectList;
                        });
                        return obj;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    // 职位关键词列表
    const { data: keywords, loading: keywordLoading, run: fetchKeywords, mutate: resetKeywords } = useRequest(
        getPositionKeywords,
        {
            manual: true,
            initialData: [],
            ...defaultFormatResult
        }
    );

    // 职位亮点列表
    const { data: points, loading: pointLoading, run: fetchPoints } = useRequest(queryChannelDicts, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return resData?.[0]?.channelSelectList || [];
                }
                message.error(msg);
            }
            return [];
        }
    });

    // 保存字段配置
    const { loading: submitLoading, run: addField } = useRequest(addFieldSet, {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                message.success('操作成功');
                if (onRefresh) {
                    onRefresh();
                }
                setVisible(false);
            } else {
                message.error(msg);
            }
        }
    });

    React.useEffect(() => {
        if (visible && dutyList.length === 0) {
            fetchDutyList({ postName: '', pageSize: 99999 });
        }
        if (visible && categoryTree?.length === 0) {
            fetchCategoryTree(type);
        }
        if (visible && type === 'liepin' && points?.length === 0) {
            fetchPoints([
                {
                    channelCode: type,
                    categoryCode: 'positionPoint'
                }
            ]);
        }
        if (visible && type === 'linkedin') {
            fetchLinkedInKeywords();
        }
        if (!visible) {
            form.resetFields();
        }
    }, [visible]);

    React.useImperativeHandle(ref, () => ({
        show: dataVal => {
            setData(dataVal);
            setVisible(true);
        }
    }));

    const handleOk = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                // console.log(values);
                const { skillList = [], positionPointList = [], positionPointName, ...rest } = values;
                if (type === 'lagou' && skillList.length > 4) {
                    message.error('职位关键词不可超过4个');
                    return;
                }
                if (type === 'linkedin' && skillList.length > 10) {
                    message.error('The count of Target your job post cannot exceed 10');
                    return;
                }
                if (type !== 'linkedin' && skillList.length > 8) {
                    message.error('职位关键词不可超过8个');
                    return;
                }
                if (type !== 'lagou' && positionPointList.length > 10) {
                    message.error('职位亮点不可超过10个');
                    return;
                }
                addField({
                    ...rest,
                    skillList,
                    positionPointList: type === 'lagou' ? [positionPointName] : positionPointList,
                    channelCode: type
                });
            }
        });
    };

    const handleCancel = () => {
        setVisible(false);
    };

    const handleChange = keys => {
        if (type === 'bosszp' || type === 'lagou' || type === 'mmzp') {
            if (keys && keys.length > 0) {
                fetchKeywords({
                    channelCode: type,
                    positionCategoryCodeList: keys
                });
            } else {
                resetKeywords([]);
            }
            form.setFieldsValue({
                skillList: undefined
            });
        }
    };

    const formLayout = {
        wrapperCol: { span: 15 },
        labelCol: { span: 6 }
    };

    return (
        <Modal
            width={800}
            title={data?.id ? '编辑配置' : '添加配置'}
            visible={visible}
            destroyOnClose
            onOk={handleOk}
            onCancel={handleCancel}
            confirmLoading={submitLoading}
        >
            <Form {...formLayout} style={{ marginTop: 24 }}>
                <Form.Item label={FORM_TITLE[type]?.title || '招聘职位'}>
                    <Spin spinning={dutyLoading}>
                        {getFieldDecorator('positionCodeList', {
                            initialValue: undefined,
                            rules: [
                                {
                                    required: true,
                                    message: `${FORM_TITLE[type]?.title || '招聘职位'}${FORM_TITLE[type]?.notNull ||
                                        '不能为空'}`
                                }
                            ]
                        })(
                            <Select
                                mode="multiple"
                                placeholder={`${FORM_TITLE[type]?.select || '请选择'}${FORM_TITLE[type]?.title ||
                                    '招聘职位'}`}
                                style={{ width: '100%' }}
                                allowClear
                                showSearch
                                optionFilterProp="label"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            >
                                {dutyList?.map(item => (
                                    <Option
                                        value={item.positionCode}
                                        key={item.positionCode}
                                        label={item.positionName}
                                        disabled={disabledPositionList.includes(item.positionCode)}
                                    >
                                        {item.positionName}
                                        {item.rankValue ? '/' : ''}
                                        {item.rankValue}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Spin>
                </Form.Item>
                <Form.Item label={FORM_TITLE[type]?.category || '职位类别'}>
                    <Spin spinning={categoryLoading}>
                        {getFieldDecorator('positionCategoryList', {
                            initialValue: undefined,
                            rules: [
                                {
                                    required: true,
                                    message: `${FORM_TITLE[type]?.category || '职位类别'}${FORM_TITLE[type]?.notNull ||
                                        '不能为空'}`
                                }
                            ]
                        })(
                            <DropDownCascader
                                options={categoryTree}
                                placeholder={`${FORM_TITLE[type]?.select || '请选择'}${FORM_TITLE[type]?.category ||
                                    '职位类别'}`}
                                maxCount={MAX_COUNT[type]}
                                changeOnLastLevel={LAST_LEVEL[type]}
                                onChange={handleChange}
                            />
                        )}
                    </Spin>
                </Form.Item>
                {(type === 'bosszp' || type === 'lagou') && (
                    <Form.Item label={FORM_TITLE[type]?.skill || '职位关键词'}>
                        <Spin spinning={keywordLoading}>
                            {getFieldDecorator('skillList', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: `${FORM_TITLE[type]?.skill || '职位关键词'}不能为空`
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            if (value && value.length > SKILL_MAX[type]) {
                                                callback(
                                                    `${FORM_TITLE[type]?.skill || '职位关键词'}不可超过${
                                                        SKILL_MAX[type]
                                                    }个`
                                                );
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Select
                                    mode="tags"
                                    showSearch
                                    allowClear
                                    style={{ width: '100%' }}
                                    placeholder={`请选择或输入${FORM_TITLE[type]?.skill || '职位关键词'}`}
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {keywords?.map(item => (
                                        <Option
                                            value={item.skill}
                                            key={item.skill}
                                            disabled={
                                                form.getFieldValue('skillList')?.length >= SKILL_MAX[type] &&
                                                !form.getFieldValue('skillList')?.includes(item.skill)
                                            }
                                        >
                                            {item.skill}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                )}
                {type === 'linkedin' && (
                    <Form.Item label={FORM_TITLE[type]?.skill || 'Target your job post'}>
                        <Spin spinning={linkedInKeywordsLoading}>
                            {getFieldDecorator('skillList', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: `${FORM_TITLE[type]?.skill || 'Target your job post'}${FORM_TITLE[type]
                                            ?.notNull || '不能为空'}`
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            if (value && value.length > SKILL_MAX[type]) {
                                                callback(
                                                    `${FORM_TITLE[type]?.skill ||
                                                        'Target your job post'} cannot exceed ${SKILL_MAX[type]}`
                                                );
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Select
                                    mode="multiple"
                                    showSearch
                                    allowClear
                                    style={{ width: '100%' }}
                                    placeholder={`${FORM_TITLE[type]?.select || '请选择'}${FORM_TITLE[type]?.skill ||
                                        'Target your job post'}`}
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {linkedInKeywords?.positionKeyword?.map(item => (
                                        <Option
                                            value={item.selectName}
                                            key={item.selectName}
                                            disabled={
                                                form.getFieldValue('skillList')?.length >= SKILL_MAX[type] &&
                                                !form.getFieldValue('skillList')?.includes(item.selectName)
                                            }
                                        >
                                            {item.selectName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                )}
                {type === 'linkedin' && (
                    <Form.Item label={FORM_TITLE[type]?.project || 'Add to a project'}>
                        <Spin spinning={linkedInKeywordsLoading}>
                            {getFieldDecorator('projectInfoList', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: `${FORM_TITLE[type]?.project || 'Add to a project'}${FORM_TITLE[type]
                                            ?.notNull || '不能为空'}`
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            const reg = new RegExp('[\u4E00-\u9FFF]');
                                            if (value && reg.test(value?.join(''))) {
                                                callback('Project cannot enter Chinese');
                                                return;
                                            }
                                            if (value?.length > 1) {
                                                callback('The count of Project cannot exceed 1');
                                                return;
                                            }
                                            if (value?.[0] && value?.[0].length > 60) {
                                                callback('The length of Project cannot exceed 60');
                                                return;
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Select
                                    mode="tags"
                                    showSearch
                                    allowClear
                                    style={{ width: '100%' }}
                                    placeholder={`${FORM_TITLE[type]?.selectInput || '请选择或输入'}${FORM_TITLE[type]
                                        ?.project || '职位关键词'}`}
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {linkedInKeywords?.projectInfo?.map(item => (
                                        <Option
                                            value={item.selectName}
                                            key={item.selectName}
                                            disabled={
                                                form.getFieldValue('projectInfoList')?.length >= 1 &&
                                                !form.getFieldValue('projectInfoList')?.includes(item.selectName)
                                            }
                                        >
                                            {item.selectName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                )}
                {type === 'mmzp' && (
                    <Form.Item label="行业方向">
                        <Spin spinning={keywordLoading}>
                            {getFieldDecorator('skillList', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '行业方向不能为空'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            if (value && value.length > SKILL_MAX[type]) {
                                                callback(`行业方向不可超过${SKILL_MAX[type]}个`);
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Select
                                    mode="multiple"
                                    showSearch
                                    allowClear
                                    style={{ width: '100%' }}
                                    placeholder="请选择行业方向"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {keywords?.map(item => (
                                        <Option
                                            value={item.skill}
                                            key={item.skill}
                                            disabled={
                                                form.getFieldValue('skillList')?.length >= SKILL_MAX[type] &&
                                                !form.getFieldValue('skillList')?.includes(item.skill)
                                            }
                                        >
                                            {item.skill}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                )}
                {type === 'liepin' && (
                    <Form.Item label="职位亮点">
                        <Spin spinning={pointLoading}>
                            {getFieldDecorator('positionPointList', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '职位亮点不能为空'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            if (value && value.length > 10) {
                                                callback('职位亮点不可超过10个');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Select
                                    mode="tags"
                                    showSearch
                                    allowClear
                                    style={{ width: '100%' }}
                                    placeholder="请选择或输入职位亮点"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {points?.map(item => (
                                        <Option
                                            value={item.selectName}
                                            key={item.selectName}
                                            disabled={
                                                form.getFieldValue('positionPointList')?.length >= 10 &&
                                                !form.getFieldValue('positionPointList')?.includes(item.selectName)
                                            }
                                        >
                                            {item.selectName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                )}
                {type === 'lagou' && (
                    <Form.Item label="职位亮点">
                        {getFieldDecorator('positionPointName', {
                            initialValue: undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '职位亮点不能为空'
                                }
                            ]
                        })(<Input placeholder="请输入职位亮点" maxLength={20} />)}
                    </Form.Item>
                )}
            </Form>
        </Modal>
    );
});

export default Form.create({})(FieldModal);
